<?php
include_once(_CORE_PATH. "mapper_prototype.php");
include_once(_APP_PATH. "business/comments/comments_entity.php");
class CommentsMapper extends mapper_prototype
{
	private $_entryId = 0;
	private $_source;
	
	public function __construct($entryId)
	{
		parent::__construct('comments');
		$this->_entryId = (int)$entryId;
		
		$this->_source = MozgSource::get('default');
	}	
	
	static public function GetInstance($entryId)
	{
		return new self($entryId);		
	}

	public function GetById($id)
	{
          return $this->_source->query("SELECT
												maec.id,
												maec.entry_id,
												maec.message,
												maec.date_created dateCreated,
												maec.user_id userId,
												u.username userName,
												u.avatar									   
						                     FROM
						                     	%%article_entry_comment%% maec
						                     		left join %%users%% u on (maec.user_id = u.user_id)
						                     WHERE
						                     	id=" . (int)$id . " and
						                     	entry_id = " .$this->_entryId. "
						                    ")->fetchObject('CommentsEntity');		
	}

	public function GetNew()
	{
		return new CommentsEntity();
	} 
		
	private $_totalRows = 0;
	
	public function GetTotal()
	{
		return $this->_totalRows;		
	}
	
	public function GetComments()
	{   
        $stmt = $this->_source->query("SELECT SQL_CALC_FOUND_ROWS
												maec.id,
												maec.entry_id,
												maec.message,
												maec.date_created dateCreated,
												maec.user_id userId,
												u.username userName,
												u.avatar									   
						                     FROM
						                     	%%article_entry_comment%% maec
						                     		left join %%users%% u on (maec.user_id = u.user_id)
						                     WHERE
						                     	entry_id = " .$this->_entryId. "
							               ");

        $this->_totalRows = $this->_source->query("SELECT FOUND_ROWS()")->fetchColumn();
        
	    $stmt->setFetchMode(PDO::FETCH_CLASS, 'CommentsEntity');
        return $stmt->fetchAll();		
	}	

	public function Save(CommentsEntity $obj)
	{
		if (!$this->Prepare($obj)) return false;
		return $this->Insert($obj);
	}
	
	private function Insert(CommentsEntity $obj)
	{		
		$num = $this->_source->exec("insert into %%article_entry_comment%%(entry_id, message, date_created, user_id)
			            values(
					              " .$this->_entryId. ",
					              " .$this->_source->quote($obj->GetMessage()). ",
					              NOW(),
					              " .$obj->GetUserId(). "
			            )
			");		

		if ($num)
		{
			$this->UpdateCommentsNum(+1);
			$obj->SetId($this->_source->lastInsertID());
			return true;
		}
			
		return false;
	}

	private function Prepare(CommentsEntity $obj)
	{
		if (strlen($obj->GetMessage()) < 1) 
		{
            return $this->SetErrorMessage('Введите комментарий');
        }

        return true;
	}

    public function Delete($id)
    {
        $num = (bool)$this->_source->exec("DELETE 
		        								FROM %%article_entry_comment%%
		        								WHERE 
		        									id=" .(int)$id. " and
		        									entry_id = " .$this->_entryId. "
		        								"); 
        if ($num)
        {
        	$this->UpdateCommentsNum(-1);
        	return true;  
        }
        
        return false;
    } 

    public function DeleteAll()
    {
        $num = (bool)$this->_source->exec("DELETE 
		        								FROM %%article_entry_comment%%
		        								WHERE 
		        									entry_id = " .$this->_entryId. "
		        								");  
        if ($num)
        {
        	$this->UpdateCommentsNum(0, false);
        	return true;  
        }
        
        return false;         
    } 
    
    private function UpdateCommentsNum($num, $relative = true)
    {
		return (bool)$this->_source->exec("update %%article_entry%%
										      set
									              comments_num = " .($relative ? 'comments_num +' : ''). " " .(int)$num. "
										      where 
										      	  id=" .$this->_entryId. "
									     ");	    	    
    }
}	